//
//  CAReturnGoodsViewController.m
//  LNH
//
//  Created by twentylx on 2018/2/24.
//  Copyright © 2018年 twentylx. All rights reserved.
//

#import "CAReturnGoodsViewController.h"
#import "CAReturnGoodsView.h"
#import "CAReturnStatusView.h"
#import "CAImageView.h"
#import "CAReturnGoodsApi.h"

@interface CAReturnGoodsViewController () <UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate> {
    NSString *_status;
    UIImage *_image1;
    UIImage *_image2;
    UIImage *_image3;
}

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIView *containterView;

@property (nonatomic, strong) CAReturnGoodsView *goodsView;
@property (nonatomic, strong) CAReturnStatusView *statusView;
@property (nonatomic, strong) CAImageView *returnImageView;

@property (nonatomic, strong) UIView *selectStatusView;
@property (nonatomic, strong) UILabel *statusTitleLabel;
@property (nonatomic, strong) UITableView *statusTableView;
@property (nonatomic, strong) NSArray *statusArray;
@property (nonatomic, strong) UIButton *statusCloseButton;

@property (nonatomic, strong) UIView *reasonView;
@property (nonatomic, strong) UILabel *reasonTitleLabel;
@property (nonatomic, strong) UITableView *reasonTableView;
@property (nonatomic, strong) NSArray *reasonArray;
@property (nonatomic, strong) UIButton *reasonCloseButton;


@property (nonatomic,strong) UIAlertController *pickAlertController;
@property (nonatomic,strong) UIImagePickerController *imagePickerController;

@property (nonatomic, strong) UIButton *submitButton;

@end

static NSString *reasonCellIdentifier = @"reasonCell";
static NSString *statusCellIdentifier = @"statusCell";

@implementation CAReturnGoodsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/// 初始化数据
- (void)lm_initialDefaultsForController {
    _statusArray = @[
                     @{@"name":@"已收到货",@"status":@"1"},
                     @{@"name":@"未收到货",@"status":@"0"},
                     ];
    
    _reasonArray = @[
                     @{@"reason":@"退运费"},
                     @{@"reason":@"型号/颜色与商品页面不符合"},
                     @{@"reason":@"功能/功效不符合"},
                     @{@"reason":@"质量问题"},
                     @{@"reason":@"其他"},
                     ];
}

/// 绑定 vm
- (void)lm_bindViewModelForController {
    
}

/// 创建视图
- (void)lm_createViewForController {
    [self.view setNeedsUpdateConstraints];
    
    [self.view addSubview:self.scrollView];
    [self.scrollView addSubview:self.containterView];
    
    [self.containterView addSubview:self.goodsView];
    [self.containterView addSubview:self.statusView];
    [self.containterView addSubview:self.returnImageView];
    
    [self.view addSubview:self.selectStatusView];
    [self.selectStatusView addSubview:self.statusTitleLabel];
    [self.selectStatusView addSubview:self.statusTableView];
    [self.selectStatusView addSubview:self.statusCloseButton];
    
    [self.view addSubview:self.reasonView];
    [self.reasonView addSubview:self.reasonTitleLabel];
    [self.reasonView addSubview:self.reasonTableView];
    [self.reasonView addSubview:self.reasonCloseButton];
    
    [self.view addSubview:self.submitButton];
}

/// 配置导航栏
- (void)lm_configNavigationForController {
    self.navigationItem.title = @"申请退款";
}

#pragma mark - Layout

- (void)updateViewConstraints
{
    [super updateViewConstraints];
    
    [_scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    [_containterView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.scrollView);
        make.width.equalTo(self.scrollView);
    }];
    
    [_goodsView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.equalTo(self.containterView);
        make.top.equalTo(self.containterView);
        make.height.mas_equalTo(150);
    }];
    
    [_statusView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.equalTo(self.containterView);
        make.top.equalTo(self.goodsView.mas_bottom).offset(10);
        make.height.mas_equalTo(230);
    }];
    
    [_returnImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.equalTo(self.containterView);
        make.top.equalTo(self.statusView.mas_bottom).offset(10);
        make.height.mas_equalTo(130);
    }];
    
    [_containterView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.returnImageView.mas_bottom).offset(50);
    }];
    
    /**
     *货物状态弹出框
     **/
    [_selectStatusView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.top.equalTo(self.view.mas_bottom);
        make.width.mas_equalTo(SCREEN_WIDTH);
        make.height.mas_equalTo(SCREEN_HEIGHT/2);
    }];
    
    [_statusTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.selectStatusView);
        make.top.equalTo(self.selectStatusView).offset(20);
    }];
    
    [_statusTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.equalTo(self.selectStatusView);
        make.top.equalTo(self.statusTitleLabel.mas_bottom);
        make.bottom.equalTo(self.statusCloseButton.mas_top);
    }];
    
    [_statusCloseButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.equalTo(self.selectStatusView);
        if (isIPhoneX) {
            make.bottom.equalTo(self.selectStatusView).offset(-34);
        } else {
            make.bottom.equalTo(self.selectStatusView);
        }
        make.height.mas_equalTo(44);
    }];
    
    /**
     *退款原因弹出框
    **/
    [_reasonView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.top.equalTo(self.view.mas_bottom);
        make.width.mas_equalTo(SCREEN_WIDTH);
        make.height.mas_equalTo(SCREEN_HEIGHT/2);
    }];
    
    [_reasonTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.reasonView);
        make.top.equalTo(self.reasonView).offset(20);
    }];
    
    [_reasonTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.equalTo(self.reasonView);
        make.top.equalTo(self.reasonTitleLabel.mas_bottom);
        make.bottom.equalTo(self.reasonCloseButton.mas_top);
    }];
    
    [_reasonCloseButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.equalTo(self.reasonView);
        if (isIPhoneX) {
            make.bottom.equalTo(self.reasonView).offset(-34);
        } else {
            make.bottom.equalTo(self.reasonView);
        }
        make.height.mas_equalTo(44);
    }];
    
    [_submitButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.equalTo(self.view);
        if (isIPhoneX) {
            make.bottom.equalTo(self.view).offset(-34);
        } else {
            make.bottom.equalTo(self.view);
        }
        make.height.mas_equalTo(44);
    }];
}

#pragma mark get & set
- (UIScrollView *) scrollView {
    if (!_scrollView) {
        _scrollView = [UIScrollView new];
        _scrollView.backgroundColor = RGBCOLOR(241, 241, 241);
    }
    return _scrollView;
}

- (UIView *) containterView {
    if (!_containterView) {
        _containterView = [UIView new];
        _containterView.backgroundColor = [UIColor clearColor];
    }
    return _containterView;
}

- (CAReturnGoodsView *)goodsView {
    if (!_goodsView) {
        _goodsView = [CAReturnGoodsView new];
        [_goodsView.goodsImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@", BASE_IMAGE_DOMAIN, self.goodsDict[@"goods_img"]]]];
        _goodsView.nameLabel.text = self.goodsDict[@"goods_name"];
        NSArray *attrArray = self.goodsDict[@"attr"];
        __block NSString *attrStr = @"";
        [attrArray enumerateObjectsUsingBlock:^(NSDictionary *attrDict, NSUInteger idx, BOOL * _Nonnull stop) {
            attrStr = [NSString stringWithFormat:@"%@ %@:%@", attrStr, attrDict[@"name"], attrDict[@"attr_value"]];
        }];
        self.goodsView.sizeLabel.text = attrStr;
        self.goodsView.priceLabel.text = [NSString stringWithFormat:@"￥%@", self.goodsDict[@"goods_price"]];
    }
    return _goodsView;
}

- (CAReturnStatusView *)statusView {
    if (!_statusView) {
        _statusView = [CAReturnStatusView new];
        //货物状态
        UITapGestureRecognizer *orderStatusTap = [UITapGestureRecognizer new];
        [_statusView.orderStatusView addGestureRecognizer:orderStatusTap];
        [[orderStatusTap rac_gestureSignal] subscribeNext:^(__kindof UIGestureRecognizer * _Nullable x) {
            [self showStatusView];
            [self hideReasonView];
        }];
        //退款原因
        UITapGestureRecognizer *returnReasonTap = [UITapGestureRecognizer new];
        [_statusView.returnReasonView addGestureRecognizer:returnReasonTap];
        [[returnReasonTap rac_gestureSignal] subscribeNext:^(__kindof UIGestureRecognizer * _Nullable x) {
            [self showReasonView];
            [self hideStautsView];
        }];
    }
    return _statusView;
}

- (CAImageView *)returnImageView {
    if (!_returnImageView) {
        _returnImageView = [CAImageView new];
        UITapGestureRecognizer *gesture = [UITapGestureRecognizer new];
        [_returnImageView.returnImageView addGestureRecognizer:gesture];
        [[gesture rac_gestureSignal] subscribeNext:^(__kindof UIGestureRecognizer * _Nullable x) {
            [self presentViewController:self.pickAlertController animated:YES completion:nil];
        }];
    }
    return _returnImageView;
}

/**
 *货物状态弹出框
 **/
- (UIView *)selectStatusView {
    if (!_selectStatusView) {
        _selectStatusView = [[UIView alloc] init];
        _selectStatusView.backgroundColor = [UIColor whiteColor];
    }
    return _selectStatusView;
}

- (UILabel *)statusTitleLabel {
    if (!_statusTitleLabel) {
        _statusTitleLabel = [[UILabel alloc] init];
        _statusTitleLabel.text = @"货物状态";
        _statusTitleLabel.textAlignment = NSTextAlignmentCenter;
        _statusTitleLabel.font = [UIFont systemFontOfSize:16];
    }
    return _statusTitleLabel;
}

- (UITableView *) statusTableView {
    if (!_statusTableView) {
        _statusTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        [_statusTableView setBackgroundColor:[UIColor whiteColor]];
        _statusTableView.dataSource = self;
        _statusTableView.delegate = self;
        _statusTableView.tag = 20;
    }
    return _statusTableView;
}

- (UIButton *)statusCloseButton {
    if (!_statusCloseButton) {
        _statusCloseButton = [UIButton new];
        [_statusCloseButton setTitle:@"关闭" forState:UIControlStateNormal];
        [_statusCloseButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _statusCloseButton.titleLabel.font = [UIFont systemFontOfSize:20];
        _statusCloseButton.backgroundColor = RGBCOLOR(233, 85, 19);
        [[_statusCloseButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            [self hideStautsView];
        }];
    }
    return _statusCloseButton;
}

/**
 *退款原因弹出框
 **/
- (UIView *)reasonView {
    if (!_reasonView) {
        _reasonView = [[UIView alloc] init];
        _reasonView.backgroundColor = [UIColor whiteColor];
    }
    return _reasonView;
}

- (UILabel *)reasonTitleLabel {
    if (!_reasonTitleLabel) {
        _reasonTitleLabel = [[UILabel alloc] init];
        _reasonTitleLabel.text = @"退款原因";
        _reasonTitleLabel.textAlignment = NSTextAlignmentCenter;
        _reasonTitleLabel.font = [UIFont systemFontOfSize:16];
    }
    return _reasonTitleLabel;
}

- (UITableView *) reasonTableView {
    if (!_reasonTableView) {
        _reasonTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        [_reasonTableView setBackgroundColor:[UIColor whiteColor]];
        _reasonTableView.dataSource = self;
        _reasonTableView.delegate = self;
        _reasonTableView.tag = 10;
    }
    return _reasonTableView;
}

- (UIButton *)reasonCloseButton {
    if (!_reasonCloseButton) {
        _reasonCloseButton = [UIButton new];
        [_reasonCloseButton setTitle:@"关闭" forState:UIControlStateNormal];
        [_reasonCloseButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _reasonCloseButton.titleLabel.font = [UIFont systemFontOfSize:20];
        _reasonCloseButton.backgroundColor = RGBCOLOR(233, 85, 19);
        [[_reasonCloseButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            [self hideReasonView];
        }];
    }
    return _reasonCloseButton;
}

- (UIButton *)submitButton {
    if (!_submitButton) {
        _submitButton = [UIButton new];
        [_submitButton setTitle:@"提交" forState:UIControlStateNormal];
        _submitButton.backgroundColor = RGBCOLOR(233, 85, 19);
        _submitButton.titleLabel.font = [UIFont systemFontOfSize:20];
        
        [[_submitButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            [self submitAction];
        }];
    }
    return _submitButton;
}

/**
 *上传图片
 **/
-(UIAlertController *)pickAlertController{
    if (!_pickAlertController) {
        _pickAlertController = [UIAlertController alertControllerWithTitle:@"修改头像" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        @weakify(self);
        UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            @strongify(self);
            self.imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentViewController:self.imagePickerController animated:YES completion:nil];
        }];
        UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            @strongify(self);
            self.imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:self.imagePickerController animated:YES completion:nil];
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [_pickAlertController addAction:albumAction];
        [_pickAlertController addAction:cameraAction];
        [_pickAlertController addAction:cancelAction];
    }
    return _pickAlertController;
}

-(UIImagePickerController *)imagePickerController{
    if (!_imagePickerController) {
        _imagePickerController = [[UIImagePickerController alloc] init];
        _imagePickerController.allowsEditing = YES;
        _imagePickerController.delegate = self;
    }
    return _imagePickerController;
}

#pragma mark private method
//退款原因动画设置
- (void) showReasonView {
    _submitButton.hidden = YES;
    [UIView animateWithDuration:0.3 animations:^{
        if (isIPhoneX) {
            _reasonView.frame = CGRectMake(0, SCREEN_HEIGHT - SCREEN_HEIGHT * 0.5 - 88, SCREEN_WIDTH, SCREEN_HEIGHT * 0.5);
        } else {
            _reasonView.frame = CGRectMake(0, SCREEN_HEIGHT - SCREEN_HEIGHT * 0.5 - 54, SCREEN_WIDTH, SCREEN_HEIGHT * 0.5);
        }
    }];
}

- (void) hideReasonView {
    _submitButton.hidden = NO;
    [UIView animateWithDuration:0.3 animations:^{
        _reasonView.transform = CGAffineTransformTranslate(_reasonView.transform, 0, SCREEN_HEIGHT * 0.5);
    }];
}

//货物状态动画设置
- (void) showStatusView {
    _submitButton.hidden = YES;
    [UIView animateWithDuration:0.3 animations:^{
        if (isIPhoneX) {
            _selectStatusView.frame = CGRectMake(0, SCREEN_HEIGHT - SCREEN_HEIGHT * 0.5 - 88, SCREEN_WIDTH, SCREEN_HEIGHT * 0.5);
        } else {
            _selectStatusView.frame = CGRectMake(0, SCREEN_HEIGHT - SCREEN_HEIGHT * 0.5 - 54, SCREEN_WIDTH, SCREEN_HEIGHT * 0.5);
        }
    }];
}

- (void) hideStautsView {
    _submitButton.hidden = NO;
    [UIView animateWithDuration:0.3 animations:^{
        _selectStatusView.transform = CGAffineTransformTranslate(_selectStatusView.transform, 0, SCREEN_HEIGHT * 0.5);
    }];
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    if (_image3 == nil) {
        _image3 = info[UIImagePickerControllerOriginalImage];
        _returnImageView.return3ImageView.image = _image3;
    } else if (_image2 == nil) {
        _image2 = info[UIImagePickerControllerOriginalImage];
        _returnImageView.return2ImageView.image = _image2;
    } else if (_image1 == nil) {
        _image1 = info[UIImagePickerControllerOriginalImage];
        _returnImageView.return1ImageView.image = _image1;
    } else {
        [SVProgressHUD lm_displayErrorWithStatus:@"最多上传三张图片"];
    }
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void) submitAction {
    NSString *goodsId = [NSString stringWithFormat:@"%ld", [self.goodsDict[@"id"] integerValue]];
    NSString *reason = self.statusView.returnReasonSelectLabel.text;
    NSString *content = self.statusView.returnSpeakTextView.text;
    if (IsStrEmpty(_status)) {
        [SVProgressHUD lm_displayErrorWithStatus:@"请选择货物状态"];
        return;
    }
    if (IsStrEmpty(reason)) {
        [SVProgressHUD lm_displayErrorWithStatus:@"请选择退款原因"];
        return;
    }
    CAReturnGoodsApi *returnGoodsApi = [[CAReturnGoodsApi alloc] initWithOrderId:self.orderId orderGoodsId:goodsId GoodsStatus:_status Reason:reason Content:content Image1:_image1 Image2:_image2 Image3:_image3];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [returnGoodsApi startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        CAReturnGoodsApi *api = (CAReturnGoodsApi *) request;
        if (api.done) {
            [SVProgressHUD lm_displaySuccessWithStatus:@"申请成功，请等待客服审核！"];
            [self.navigationController popViewControllerAnimated:YES];
        } else {
            [SVProgressHUD lm_displayErrorWithStatus:api.errorMsg];
        }
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [SVProgressHUD lm_displayErrorWithStatus:@"请求出错"];
    }];
}

#pragma mark UITableView DataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView.tag == 10) {
        return self.reasonArray.count;
    } else if (tableView.tag == 20) {
        NSLog(@"%ld", self.statusArray.count);
        return self.statusArray.count;
    } else {
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"%ld", tableView.tag);
    if (tableView.tag == 10) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reasonCellIdentifier];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reasonCellIdentifier];
        }
        NSDictionary *dict = self.reasonArray[indexPath.row];
        cell.textLabel.text = dict[@"reason"];
        cell.textLabel.font = [UIFont systemFontOfSize:14];

        return cell;
    } else if (tableView.tag == 20) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:statusCellIdentifier];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:statusCellIdentifier];
        }
        NSDictionary *dict =  self.statusArray[indexPath.row];
        cell.textLabel.text = dict[@"name"];
        cell.textLabel.font = [UIFont systemFontOfSize:14];
        
        return cell;
    } else {
        return nil;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44;
}

-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    _submitButton.hidden = NO;
    if (tableView.tag == 10) {
        NSDictionary *dict = self.reasonArray[indexPath.row];
        self.statusView.returnReasonSelectLabel.text = dict[@"reason"];
        [self hideReasonView];
    } else {
        NSDictionary *dict = self.statusArray[indexPath.row];
        self.statusView.orderStatusSelectLabel.text = dict[@"name"];
        _status = dict[@"status"];
        [self hideStautsView];
    }
    
}


@end
